#include <stdio.h>      
#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h> 
#include <string.h> 
#include <arpa/inet.h>
#include <string>
#include <assert.h>

std::string networkIpAddr()
{
  std::string retVal("aaa.bbb.ccc.ddd");
  struct ifaddrs * ifAddrStruct=NULL;
  void * tmpAddrPtr=NULL;

  const int ret=getifaddrs(&ifAddrStruct);
  assert(ret==0);
  for (struct ifaddrs* ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
    if (ifa ->ifa_addr->sa_family==AF_INET) { // check it is IP4
        // is a valid IP4 Address
        tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
        char addressBuffer[INET_ADDRSTRLEN];
        inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
        //printf("(%s:%d) %s IP Address %s\n",__FILE__,__LINE__, ifa->ifa_name, addressBuffer);
        //break after finding network device that isn't the loopback and prepare to return it
        if(strcmp(ifa->ifa_name,"lo"))
        {
          retVal=addressBuffer;
          break;
        }
    } else if (ifa->ifa_addr->sa_family==AF_INET6) { // check it is IP6
        // is a valid IP6 Address
        tmpAddrPtr=&((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
        char addressBuffer[INET6_ADDRSTRLEN];
        inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
        //printf("(%s:%d) %s IP Address %s\n",__FILE__,__LINE__, ifa->ifa_name, addressBuffer);
    }
  }


  return retVal;
}

int main (int argc, const char * argv[]) {
  printf("(%s:%d) main process initializing\n",__FILE__,__LINE__);
  std::string netAddr = networkIpAddr();
  printf("(%s:%d) network address: '%s'\n",__FILE__,__LINE__,netAddr.c_str());
  printf("(%s:%d) main process terminating\n",__FILE__,__LINE__);
}
